<?php

namespace Buu\Modules\Constant\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use App\Models\ConstantType;
use Illuminate\Http\Request;
use App\Models\ConstantValue;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use App\Admin\Extensions\Tools\UserButton;

class ConstantValueController extends Controller
{

    public function index(Request $request, Content $content, $id)
    {
        return $content
            ->header('常量管理列表')
            ->breadcrumb(
                ['text' => '常量列表', 'url' => '/Constant/constant-type/list'],
                ['text' => '常量值']
            )
            ->body($this->grid($id));
    }

    /**
     * 列表构建
     *
     * @return Grid
     */
    protected function grid($id)
    {
        $grid = new Grid(new ConstantValue());
        $grid->model()->where('constant_type_id', $id)->orderBy('id');
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableBatchActions();
        $grid->disableCreateButton();
        $grid->disablePagination();

        $grid->column('constant_type_id', '常量类型')->display(function () {
            return ConstantType::where('id', $this->constant_type_id)->pluck('name');
        })->label();
        $grid->column('name', '常量名称');
        $grid->column('value', '常量值');
        $grid->column('desc', '常量描述');

        $grid->tools(function (Grid\Tools $tool) use ($id) {
            $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增常量值', '',
                url('/admin/Constant/constant-value/add/' . $id)));
        });
        // 全部关闭
        $grid->disableActions();
        return $grid;
    }


    public static function getConstantValue(Request $request)
    {
        $instanceId = $request->get('q');
        return $aGroupData = ConstantValue::getConstantValue($instanceId);
    }


    public function add(Request $request, Content $content, $id)
    {
        $request = $request->all();
        return $content
            ->header('添加常量值')
            ->breadcrumb(
                ['text' => '添加常量值']
            )
            ->body(self::addAction($request, $id));
    }

    public function addAction($request, $iUid)
    {
        $aCtype = ConstantType::getOne($iUid)->toArray();

        $form = new Form(new ConstantValue());
        $form->html("<p>常量类型：" . $aCtype['name'] . "<span style='color:red;'>  不可以修改, 请仔细填写</span></p>");
        $form->hidden('constant_type_id', '选择常量类型接口名')->value($iUid);
        $form->text('name',
            '常量名称')->rules('required')->help('大写英文和_组合 ，_只能在中间')->pattern('^[A-Z]+(?:_[A-Z]+)*$')->width('300px');
        $form->text('value', '常量值')->help('注意：常量类型如果使用发号器，常量值自增，填写无效；未使用，必须填写')->width('300px');
        $form->text('desc', '常量描述')->rules('required')->width('300px');
        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();
            // 去掉`删除`按钮
            $tools->disableDelete();
            // 去掉`查看`按钮
            $tools->disableView();
        });
        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
        });
        $form->setAction('/admin/Constant/constant-value/addsave');
        return $form;
    }


    public function addsave(Request $request)
    {
        $request = $request->all();
        $aCtype = ConstantType::getOne($request['constant_type_id'])->toArray();
        $aNameData = ConstantValue::getDataByname($request['constant_type_id'], $request['name']);
        $aValueData = ConstantValue::getDataByvalue($request['constant_type_id'], $request['value']);
        if ($aNameData || $aValueData) {
            $sMsg = '常量值或者名称重复';
        }

        if ($aCtype['is_gumper'] == 1) {

            $aLastCValue = ConstantValue::getConstantList($request['constant_type_id']);
            $aLastCValue = array_values($aLastCValue);
            rsort($aLastCValue);

            $request['value'] = $aLastCValue['0'] + 1;

        } else {
            if (empty($request['value'])) {
                $sMsg = '请填写常量值';
            }
        }
        if (!empty($sMsg)) {
            admin_toastr($sMsg, 'error', ['timeOut' => 5000]);
            return redirect('/admin/Constant/constant-value/add/' . $request['constant_type_id'])->withInput();
        }

        $aValue = [
            'constant_type_id' => $request['constant_type_id'],
            'name' => $request['name'],
            'value' => $request['value'],
            'desc' => $request['desc'],
        ];
        if (ConstantValue::insert($aValue)) {
            $sMsg = 'success';
        } else {
            $sMsg = 'error';
        }

        admin_toastr($sMsg, $sMsg, ['timeOut' => 3]);
        return redirect('/admin/Constant/constant-value/list/' . $request['constant_type_id']);
    }

    public function listsave(Request $request)
    {
        $request = $request->all();
        $rs = [];
        if (!empty($request['value'])) {
            $updateData = [
                "desc" => $request['value']
            ];
            $rs = ConstantValue::saveInfo($request['pk'], $updateData);
        }

        if ($rs) {
            return response()->json(['status' => true, 'message' => '修改成功']);

        } else {
            return response()->json(['status' => false, 'message' => '修改失败']);
        }
    }
}